//
//  CommonTools.m
//  WTM
//
//  Created by lxj on 2017/11/30.
//  Copyright © 2017年 付凡. All rights reserved.
//

#import "CommonTools.h"

@implementation CommonTools

//获取当前屏幕显示的viewcontroller
+ (UIViewController *)getCurrentVC {

    UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
    if (!window) {
        return nil;
    }
    UIView *tempView;
    for (UIView *subview in window.subviews) {
        if ([[subview.classForCoder description] isEqualToString:@"UILayoutContainerView"]) {
            tempView = subview;
            break;
        }
    }
    if (!tempView) {
        tempView = [window.subviews lastObject];
    }

    id nextResponder = [tempView nextResponder];
    while (![nextResponder isKindOfClass:[UIViewController class]] || [nextResponder isKindOfClass:[UINavigationController class]] || [nextResponder isKindOfClass:[UITabBarController class]]) {
        tempView =  [tempView.subviews firstObject];

        if (!tempView) {
            return nil;
        }
        nextResponder = [tempView nextResponder];
    }
    return  (UIViewController *)nextResponder;
}
+ (void)call:(NSString *)phone{
    UIWebView *callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",phone]]]];
    [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:callWebview];
}

#pragma mark - 清除缓存
//遍历文件夹获得文件夹大小，返回多少M
+ (float )folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]){
        return 0;
    }
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }

    return folderSize/1000000;
}
//计算文件大小
+ (float)fileSizeAtPath:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];

    if([fileManager fileExistsAtPath:path]){
        NSInteger size = [fileManager attributesOfItemAtPath:path error:nil].fileSize;
        // 返回值是字节B
        return size;
    }
    return 0;
}
///清除缓存
+ (void)clearCachesAtPath:(NSString *)folderPath callBack:(void (^)(void))callBack{
    // 清除caches文件夹内的东西
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:folderPath];
        for (NSString *p in files) {
            NSError *error;
            NSString *path = [folderPath stringByAppendingPathComponent:p];
            if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if (callBack) {
                callBack();
            }
        });
    });
}
+ (void)copyToPasteboard:(NSString *)text{
    if (text == nil || [text isEqualToString:@""]) {
        [[self getCurrentVC].view makeToast:@"没有内容"];
    }else{
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = text;
        [[self getCurrentVC].view makeToast:@"已复制到粘贴板"];
    }
}

+(NSDictionary *)getDicByUrl:(NSString *)urlStr{

    if ([urlStr containsString:@"?"]) {
        NSRange range = [urlStr rangeOfString:@"?"];//匹配得到的下标
        urlStr = [urlStr substringFromIndex:range.location + range.length];
    }
    //分割成数组
    NSArray *array = [urlStr componentsSeparatedByString:@"&"];

    //可变字典
    NSMutableDictionary *mdic = [NSMutableDictionary new];

    for (NSString *str in array) {
        if ([str containsString:@"="]) {
            NSArray *array = [str componentsSeparatedByString:@"="];
            if (array.count == 2) {
                [mdic setValue:array[1] forKey:array[0]];
            }
        }
    }
    return mdic;
}

+(NSString *)formatFloat:(double)f{
    if (fmodf(f, 1)==0) {//如果有一位小数点
        return [NSString stringWithFormat:@"%.0f",f];
    } else if (fmodf(f*10, 1)==0) {//如果有两位小数点
        return [NSString stringWithFormat:@"%.1f",f];
    } else {
        return [NSString stringWithFormat:@"%.2f",f];
    }
}

@end
